import { ESSceneObject } from 'earthsdk3';
import { defined, FeatureDetection, RuntimeError, TaskProcessor } from 'cesium';
class GaussianSplatTextureGenerator {
  static _maxSortingConcurrency = Math.max(
    //@ts-ignore
    FeatureDetection.hardwareConcurrency - 1,
    1,
  );
  static _textureTaskProcessor: TaskProcessor | undefined = undefined;
  static _taskProcessorReady = false;
  static _error: RuntimeError | undefined = undefined;
  static _getTextureTaskProcessor = function () {
    if (!defined(GaussianSplatTextureGenerator._textureTaskProcessor)) {
      const processor = new TaskProcessor(
        // "gaussianSplatTextureGenerator",
        ESSceneObject.context.getStrFromEnv("${earthsdk3-assets-script-dir}/assets/gaussianSplatting/gaussianSplatTextureGenerator.js"),
        GaussianSplatTextureGenerator._maxSortingConcurrency,
      );
      processor
        .initWebAssemblyModule({
          wasmBinaryFile: ESSceneObject.context.getStrFromEnv("${earthsdk3-assets-script-dir}/assets/gaussianSplatting/wasm_splats_bg.wasm"),
        })
        .then(function (result) {
          if (result) {
            GaussianSplatTextureGenerator._taskProcessorReady = true;
          } else {
            GaussianSplatTextureGenerator._error = new RuntimeError(
              "Gaussian splat sorter could not be initialized.",
            );
          }
        })
        .catch((error) => {
          GaussianSplatTextureGenerator._error = error;
        });
      GaussianSplatTextureGenerator._textureTaskProcessor = processor;
    }

    return GaussianSplatTextureGenerator._textureTaskProcessor;
  };
  static generateFromAttrs = function (parameters: any) {
    const textureTaskProcessor =
      GaussianSplatTextureGenerator._getTextureTaskProcessor();
    if (defined(GaussianSplatTextureGenerator._error)) {
      throw GaussianSplatTextureGenerator._error;
    }

    if (!GaussianSplatTextureGenerator._taskProcessorReady) {
      return;
    }

    const { attributes } = parameters;
    return textureTaskProcessor.scheduleTask(parameters, [
      attributes.positions.buffer,
      attributes.scales.buffer,
      attributes.rotations.buffer,
      attributes.colors.buffer,
    ]);
  };
}

export default GaussianSplatTextureGenerator;